package com.sailing.xjpb.log.config;

import com.sailing.xjpb.log.aspect.RequestLogAspect;
import com.sailing.xjpb.log.service.BusinessLoggerService;
import com.sailing.xjpb.log.service.impl.BusinessLoggerServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * log日志功能开关控制配置类 当用户设置logfilter=false时 不启动日志记录功能
 *
 * @author sutao
 * createDate 2022/9/8 22:29
 */
@Configuration
@EnableConfigurationProperties(SystemLogConfigProperties.class)
@ConditionalOnProperty(prefix = "xjpb.log", name = "enable", havingValue = "true")
@Slf4j
public class SystemLogConfig {

    @Bean(name = "businessLoggerService")
    public BusinessLoggerService getBusinessLoggerService(SystemLogConfigProperties systemLogConfigProperties) {
        ThreadPoolConfigProperties threadPoolConfigProperties = systemLogConfigProperties.getThreadPool();
        log.info("xjpb业务日志记录已开启");
        log.info("发送日志线程池参数：{}", threadPoolConfigProperties);
        return new BusinessLoggerServiceImpl(
                new ThreadPoolExecutor(threadPoolConfigProperties.getCoreSize(),
                        threadPoolConfigProperties.getMaxSize(),
                        threadPoolConfigProperties.getKeepAliveTime(),
                        TimeUnit.SECONDS,
                        new ArrayBlockingQueue<>(threadPoolConfigProperties.getBlockQueueSize()),
                        Executors.defaultThreadFactory(),
                        new ThreadPoolExecutor.AbortPolicy()));
    }


    @Bean
    public RequestLogAspect getRequestLogAspect(@Qualifier("businessLoggerService") BusinessLoggerService businessLoggerService) {
        return new RequestLogAspect(businessLoggerService);
    }


}

